package hongcaosp.app.android.video.online;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.core.breakpoint.BlockInfo;
import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo;
import com.liulishuo.okdownload.core.cause.EndCause;
import com.liulishuo.okdownload.core.listener.DownloadListener4;
import com.liulishuo.okdownload.core.listener.assist.Listener4Assist;

import java.io.File;
import java.util.List;
import java.util.Map;

import hongcaosp.app.android.R;
import hongcaosp.app.android.video.online.bean.OnlineMusic;
import xlj.lib.android.base.toastcompat.ToastManager;

public class DialogMusicDownload extends Dialog {

    private ProgressBar pb_progress;
    private TextView tv_progress;

    private boolean currDownloadOver = false;
    private long totalLength;
    private IOnDownloadListener onDownloadListener;
    private DownloadTask downloadTask;

    public DialogMusicDownload(@NonNull Context context, IOnDownloadListener onDownloadListener) {
        super(context);
        this.onDownloadListener = onDownloadListener;
        init();
    }

    private void init() {
        setContentView(R.layout.dialog_music_download);
        pb_progress = findViewById(R.id.pb_progress);
        tv_progress = findViewById(R.id.tv_progress);

        getWindow().setLayout(WindowManager.LayoutParams.WRAP_CONTENT,WindowManager.LayoutParams.WRAP_CONTENT);

        setCanceledOnTouchOutside(false);
        setCancelable(true);

        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (downloadTask != null) {
                    downloadTask.cancel();
                    if (!currDownloadOver && downloadTask.getFile().exists()) {
                        downloadTask.getFile().delete();
                    }
                    downloadTask = null;
                }
            }
        });
    }

    public void download(OnlineMusic onlineMusic) {
        File rootFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/redgrass/txvodcache/music");
        if (!rootFile.exists()) {
            rootFile.mkdirs();
        }
        File musicFile = new File(rootFile,onlineMusic.getId() + ".mp3");
        if (musicFile.exists()) {
            if (onDownloadListener != null) {
                onDownloadListener.onOver(musicFile.getAbsolutePath());
            }
            return;
        }
        downloadTask = new DownloadTask.Builder(onlineMusic.getSongUrl(),rootFile)
                .setFilename(musicFile.getName())
                .setMinIntervalMillisCallbackProcess(100)
                .setPassIfAlreadyCompleted(false)
                .build();

        downloadTask.enqueue(new DownloadListener4() {

                    @Override
                    public void infoReady(DownloadTask task, @NonNull BreakpointInfo info, boolean fromBreakpoint, @NonNull Listener4Assist.Listener4Model model) {
                        totalLength = info.getTotalLength();
                        pb_progress.setMax((int) (totalLength / 1024 / 1024));
                    }

                    @Override
                    public void progressBlock(DownloadTask task, int blockIndex, long currentBlockOffset) {

                    }

                    @Override
                    public void progress(DownloadTask task, long currentOffset) {
                        //下载进度
                        int now = (int) (currentOffset / 1024 / 1024);
                        int total = (int) (totalLength / 1024 / 1024);

                        pb_progress.setProgress(now);
                        tv_progress.setText("正在下载("+now+"/"+total+"M)");
                    }

                    @Override
                    public void blockEnd(DownloadTask task, int blockIndex, BlockInfo info) {

                    }

                    @Override
                    public void taskEnd(DownloadTask task, EndCause cause, @Nullable Exception realCause, @NonNull Listener4Assist.Listener4Model model) {
                        //下载完成
                        if (cause == EndCause.COMPLETED) {
                            currDownloadOver = true;
                            if (onDownloadListener != null) {
                                onDownloadListener.onOver(task.getFile().getAbsolutePath());
                            }
                        } if (cause == EndCause.CANCELED) {
                            ToastManager.getInstance().showToast("已取消下载");
                        }
                        dismiss();
                    }

                    @Override
                    public void taskStart(@NonNull DownloadTask task) {
                        currDownloadOver = false;
                        pb_progress.setProgress(0);
                        tv_progress.setText("正在下载");
                    }

                    @Override
                    public void connectStart(@NonNull DownloadTask task, int blockIndex, @NonNull Map<String, List<String>> requestHeaderFields) {

                    }

                    @Override
                    public void connectEnd(@NonNull DownloadTask task, int blockIndex, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields) {

                    }
                });
        show();
    }

    public interface IOnDownloadListener {
        void onOver(String filePath);
    }
}
